{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义测试数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test=[1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "计算各数值的频数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+-------+-----------+---------+--------------------+\n",
      "| Valid | Frequency | Percent | Cumulative Percent |\n",
      "+-------+-----------+---------+--------------------+\n",
      "|   1   |     5     |   33.3  |        33.3        |\n",
      "|   2   |     4     |   26.7  |        60.0        |\n",
      "|   3   |     3     |   20.0  |        80.0        |\n",
      "|   4   |     2     |   13.3  |        93.3        |\n",
      "|   5   |     1     |   6.7   |       100.0        |\n",
      "+-------+-----------+---------+--------------------+\n"
     ]
    }
   ],
   "source": [
    "from prettytable import PrettyTable #我们使用PrettyTable包来绘制表格\n",
    "data_set=set(data_test);\n",
    "size=len(data_test)\n",
    "# 计算频数\n",
    "frequency={};\n",
    "for i in data_set:\n",
    "    frequency[i]=data_test.count(i)\n",
    "# 生成频数统计表\n",
    "title=['Valid','Frequency','Percent','Cumulative Percent'] #定义表头\n",
    "table=PrettyTable(title)\n",
    "cumulative=0 #定义累积频率变量\n",
    "for key,value in frequency.items():\n",
    "    valid_percent=value/len(data_test) #计算频率\n",
    "    cumulative+=valid_percent #计算累积频率变量\n",
    "    array=[key,value,round(valid_percent*100,1),round(cumulative*100,1)]\n",
    "    table.add_row(array)\n",
    "print(table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
